﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.ExportCommand;
using B.S.BaseData.Manage.Api.Read.DTO;
using B.S.BaseData.Manage.Domain.Entities;
using Dapper;
using MediatR;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.BaseData.Manage.Api.Read.Apilaction.CoomandHandler.ExportCommandHandler
{
    public class ExportQuserCommandHandler : IRequestHandler<ExportQuserCommand, ApiReqult<List<InventoryQuserDTO>>>
    {
        private readonly IDbConnection dbConnection;

        public ExportQuserCommandHandler(IDbConnection dbConnection)
        {
            this.dbConnection = dbConnection;
        }

        /// <summary>
        /// 批量 id 查询显示
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiReqult<List<InventoryQuserDTO>>> Handle(ExportQuserCommand request, CancellationToken cancellationToken)
        {
            ApiReqult<List<InventoryQuserDTO>> result = new ApiReqult<List<InventoryQuserDTO>>();

            try
            {
                // 根据批量 Product_id 查询 Inventory 数据
                var inventorySql = $"SELECT * FROM Inventory WHERE Product_id IN @ProductIds";
                var inventories = await dbConnection.QueryAsync<Inventory>(inventorySql, new { ProductIds = request.Product_id });

                // 根据批量 Product_id 查询 Stock_operation_batch 数据
                var stockOperationBatchSql = $"SELECT * FROM Stock_operation_batch WHERE Product_id IN @ProductIds";
                var stockOperationBatches = await dbConnection.QueryAsync<Stock_operation_batch>(stockOperationBatchSql, new { ProductIds = request.Product_id });

                // 将查询结果转换为 InventoryQuserDTO
                var dtos = new List<InventoryQuserDTO>();
                foreach (var productId in request.Product_id)
                {
                    var inventory = inventories.FirstOrDefault(i => i.Product_id == productId);
                    var stockOperationBatch = stockOperationBatches.FirstOrDefault(s => s.Product_id == productId);

                    if (inventory != null || stockOperationBatch != null)
                    {
                        var dto = new InventoryQuserDTO
                        {
                            Product_id = productId,
                            Product_name = inventory?.Product_name,
                            Spec = inventory?.Spec,
                            Category = inventory?.Category,
                            Storage_unit = inventory?.Storage_unit,
                            Warehouse_id = inventory?.Warehouse_id,
                            Warehouse_name = inventory?.Warehouse_name,
                            Location_id = inventory?.Location_id,
                            Location_name = inventory?.Location_name,
                            Location_type = inventory?.Location_type,
                            Stock_quantity = inventory?.Stock_quantity,
                            upper_limit = inventory?.upper_limit,
                            lower_limit = inventory?.lower_limit,
                            Operation_date = stockOperationBatch?.Operation_date ?? default,
                            In_quantity = stockOperationBatch?.In_quantity ?? 0,
                            Out_quantity = stockOperationBatch?.Out_quantity ?? 0,
                            Batch_no = stockOperationBatch?.Batch_no,
                            Remark = stockOperationBatch?.Remark
                        };
                        dtos.Add(dto);
                    }
                }

                result.Data = dtos;
                result.Msg = ApiEnum.查询成功.ToString();
                result.Code = ApiEnum.查询成功;
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.操作失败;
                result.Msg = ex.Message;
            }

            return result;
        }
    }
}